<?php

namespace app\admin\controller\user;

use app\admin\model\Coupon;
use app\admin\model\UserCoupon;
use Exception;
use ba\Random;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use app\common\controller\Backend;
use app\admin\model\User as UserModel;
use think\db\exception\PDOException;
use think\exception\ValidateException;

class User extends Backend
{
    protected $model = null;

    protected $withJoinTable = ['group'];

    // 排除字段
    protected $preExcludeFields = ['lastlogintime', 'loginfailure', 'password', 'salt'];

    protected $quickSearchField = ['username', 'nickname', 'id'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new UserModel();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $salt = Random::build('alnum', 16);
            $passwd = encrypt_password($data['password'], $salt);

            $data = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $data['salt'] = $salt;
                $data['password'] = $passwd;
                $result = $this->model->save($data);
                Db::commit();
            } catch (ValidateException|Exception|PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit($id = null)
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if ($this->request->isPost()) {
            $password = $this->request->post('password', '');
            if ($password) {
                $this->model->resetPassword($id, $password);
            }
            parent::edit();
        }

        unset($row->salt);
        $row->password = '';
        $this->success('', [
            'row' => $row,
        ]);
    }

    /**
     * 重写select
     */
    public function select()
    {
        $this->request->filter(['strip_tags', 'trim']);

        [$where, $alias, $limit, $order] = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        foreach ($res as $re) {
            $re->nickname_text = $re->username . '(ID:' . $re->id . ')';
        }

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }

        [$where, $alias, $limit, $order] = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit)
            ->each(function ($item) {
                $item['pid'] = $this->model->where('id', $item['pid'])->value('nickname', '无');
                return $item;
            });

        $this->success('', [
            'list' => $res->items(),
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    /**
     * @param $couponIds
     * @param $ids
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function giveCoupon($couponIds, $ids)
    {
        $couponModel = new Coupon();
        $time = time();
        $couponList = $couponModel->whereIn('id', $couponIds)->select()->each(function ($coupon) use ($time) {
            if ($coupon['type'] == 0 && $coupon['start_time'] > $time && $coupon['end_time'] < $time) throw new ValidateException("优惠券「{$coupon->coupon_name}」未在有效期");
            if ($coupon['num'] <= 0) $this->error("优惠券「{$coupon->coupon_name}」数量不足");
            return $coupon;
        });
        Db::startTrans();
        try {
            $userCoupon = new UserCoupon();
            $uc = [];
            foreach ($couponList as $coupon) {
                foreach ($ids as $id) {
                    // if ($userCoupon->where([
                    //         'user_id' => $id,
                    //         'coupon_id' => $coupon->id
                    //     ])->where('updatetime', '>', 0)->count() == 0) {
                    $coupon->num -= 1;
                    $uc[] = [
                        'user_id' => $id,
                        'coupon_id' => $coupon->id,
                        'updatetime' => 0
                    ];
                    // }
                }
                if ($coupon->num < 0) throw new ValidateException("优惠券「{$coupon->coupon_name}」数量不足");
                $coupon->save();
            }
            $userCoupon->saveAll($uc);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('赠送成功');
    }
}